#include "thread_pool.h"
#include <bits/pthreadtypes.h>
//每个子线程在执行的函数执行体 start_routine
void* threadFunc(void* arg){
    //不断从任务队列中获取任务，并执行
    threadpool_t* pThreadpool = (threadpool_t*) arg;
    while(1){
        task_t* ptask = taskDeque(&pThreadpool->que); //从线程池中取出任务
        if(ptask){
            //执行业务逻辑
            doTask(ptask);
            free(ptask); //执行完释放节点
        }else{
            break;
        }
    }
    printf("sub thread %ld is exiting.\n",pthread_self());
    return NULL;

}

//线程池相关函数
int threadpoolInit(threadpool_t* pthreadpool,int num) //初始化线程池
{
    pthreadpool->pthreadNum = num;
    pthreadpool->pthreads =(pthread_t*)calloc(num,sizeof(pthread_t));
    queueInit(&pthreadpool->que);
    return 0;

}
int threadpoolDestroy(threadpool_t* pthreadpool) //销毁线程池
{
    free(pthreadpool->pthreads);
    queueDestroy(&pthreadpool->que);
    return 0;

}
int threadpoolStart(threadpool_t* pthreadpool)  //启动线程池
{
    if(pthreadpool){
        for(int i=0;i<pthreadpool->pthreadNum;++i){
            int ret = pthread_create(&pthreadpool->pthreads[i],
                                     NULL,threadFunc,pthreadpool);
            THREAD_ERROR_CHECK(ret,"pthread create");
        }

    }
}

int threadpoolStop(threadpool_t* pthreadpool)//停止线程池
{
    //如果任务队列中还有队伍，等待所有队伍执行完毕
    //再广播退出
    while(!queueIsEmpty(&pthreadpool->que)){
        sleep(1);
    }

    //发送广播，通知所有子线程退出
    broadcastAll(&pthreadpool->que);

    //回收所有子线程的资源
    for(int i=0;i<pthreadpool->pthreadNum;i++){
        pthread_join(pthreadpool->pthreads[i],NULL);
    }
    return 0;

}




